package com.scedu.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//分析性能问题
public class Test09 {
    //普通调用方式
    public static void test01(){
        User user=new User();
        long startTime=System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            user.getName();
        }
        long endTime=System.currentTimeMillis();
        System.out.println("普通方式：时间："+(endTime-startTime));
    }
    //反射调用方式
    public static void test02() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user=new User();
        Class<?> c1=Class.forName("com.scedu.reflection.User");
        Method getName = c1.getDeclaredMethod("getName");
        long startTime=System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            getName.invoke(user,null);
        }
        long endTime=System.currentTimeMillis();
        System.out.println("普通反射方式：时间："+(endTime-startTime));
    }
    //反射调用方式 关闭检测
    public static void test03() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user=new User();
        Class<?> c1=Class.forName("com.scedu.reflection.User");
        Method getName = c1.getDeclaredMethod("getName");
        getName.setAccessible(true);//关闭检测
        long startTime=System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            getName.invoke(user,null);
        }
        long endTime=System.currentTimeMillis();
        System.out.println("普通反射方式 关闭检测：时间："+(endTime-startTime));
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        test01();
        test02();
        test03();
    }
}
